﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Newtonsoft.Json.Linq;
using OfficeOpenXml.Drawing.Slicer.Style;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Tracing;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using static AutoMapper.Internal.CollectionMapperExpressionFactory;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace Coldairarrow.Business.Interface
{
    public class OL_EcommerceOrderInterfaceBusiness : Interface_BaseBusiness, IJob_Business, ITransientDependency
    {
        public List<OL_FilterDTO> Filters;
        public Base_InterfaceOption queryOption { get; set; }
        public Base_InterfaceOption insertOption { get; set; }
        public Base_InterfaceOption upDateOption { get; set; }
        public Base_InterfaceOption deleteOption { get; set; }

        public OL_EcommerceOrderInterfaceBusiness()
        {
            this.InterfaceName = "电商订单列表";
            //获取字段的映射关系
            tableField = GetMapField("editRow");
            //索引字段
            Keys = GetKeys("editRow");
            indexFields.Add(Keys.Where(X => X.Type == "K").First().Field);
            //查询过滤条件
            Filters = new List<OL_FilterDTO>();

            //数据库连接
            ConString = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
            SqlDb = (SqlServerHelper)DbHelperFactory.GetDbHelper(EFCore.Sharding.DatabaseType.SqlServer, ConString);

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            this.queryOption = this.interfaceOption.Where(o => o.OperateType == "getFilterRows").First();//查询API配置
            this.insertOption = this.interfaceOption.Where(o => o.OperateType == "addRow").First();//新增API配置
            this.upDateOption = this.interfaceOption.Where(o => o.OperateType == "editRow").First();//更行API配置
            this.deleteOption = this.interfaceOption.Where(o => o.OperateType == "deleteRow").First();//删除API配置

            //查询执行前的事件
            BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //执行非查询请求中的事件
            OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;
        }


        /// <summary>
        /// 执行非查询请求中时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="noQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, NoQueryEventArgs noQueryEventArgs)
        {
            //API请求是否成功
            noQueryEventArgs.Success = noQueryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_BeforeQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //执行查询前添加过滤条件
            if (queryEventArgs.Page.Filters.IsNullOrEmpty() && !Filters.IsNullOrEmpty())
            {
                queryEventArgs.Page.Filters = Filters;
            }

        }

        /// <summary>
        /// 查询执行中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //是否查询完成
            if (queryEventArgs.Result["data"]["rows"].ToList().Count == 0)
            {
                queryEventArgs.Page.Complete = true;
            }
            //向总行中添加新的行
            queryEventArgs.Rows.AddRange(queryEventArgs.Result["data"]["rows"].ToList());
            //获取总页数
            queryEventArgs.Page.Total = queryEventArgs.Result["data"]["total"].ToString().ToInt();
            //获取查询成功标志
            queryEventArgs.Success = queryEventArgs.Result["success"].ToString().ToBool();
        }


        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()
        {

            try
            {

                //MSKU

                //获取One_Link SKU信息
                OL_LocalSKUInterfaceBusiness localSKU = new OL_LocalSKUInterfaceBusiness();
                localSKU.Filters.Clear();
                localSKU.Filters.Add(
               //13:>,14>=15:<,16<=
               new OL_FilterDTO() { ControlId = "", DataType = 15, SpliceType = 1, FilterType = 14, Value = "" }//FDATE字段过滤日开始700天前到现在的数据
           );
                List<LocalSKU> localSKUList = await localSKU.QueryAsync<LocalSKU>(localSKU.queryOption, localSKU.tableField, localSKU.SqlDb);


                //获取店铺
                OL_ShopInterfaceBusiness OL_Shop = new OL_ShopInterfaceBusiness();
                OL_Shop.Filters.Add(
            new OL_FilterDTO() { ControlId = "", DataType = 29, SpliceType = 1, FilterType = 8, Value = "" }
                //new OL_FilterDTO() { ControlId = "661d1c34387bc49b7a55d06e", DataType = 15, SpliceType = 1, FilterType = 14, Value = "2024-11-24" }
                );
                List<OL_Shop> shopList = OL_Shop.Query<OL_Shop>(OL_Shop.queryOption, OL_Shop.tableField, OL_Shop.SqlDb);
                shopList.ForEach(x =>
                {
                    //平台
                    List<AssTable> table = x.Platform_.ToObject<List<AssTable>>();
                    if (!table.IsNullOrEmpty() && table.Count > 0) x.Platform_ = table.IsNullOrEmpty() ? "" : table.First().sid;
                });



                string firstDate = DateTime.Now.AddDays(-queryOption.ExcInterval).ToString("yyyy-MM-dd");


                List<OL_EcommerceOrder> saleskLsit = new List<OL_EcommerceOrder>();



                List<OL_EcommerceOrder> sales = new List<OL_EcommerceOrder>();
                //易仓订单
                sales = GetECOrders(firstDate.ToDateTime().Date, localSKUList, shopList);
                saleskLsit.AddRange(sales);
                //小米订单
                sales = GetXMOrders(firstDate.ToDateTime().Date, localSKUList, shopList);
                saleskLsit.AddRange(sales);
                //线下平台订单

                //亚马逊订单
                sales = GetAMZOrders(firstDate.ToDateTime().Date, localSKUList, shopList);
                saleskLsit.AddRange(sales);
                //获取OZON销售数据
                sales = GetOZOrders(firstDate.ToDateTime().Date, localSKUList, shopList);
                saleskLsit.AddRange(sales);
                //获取WB销售数据
                sales = GetWBOrders(firstDate.ToDateTime().Date, localSKUList, shopList);
                saleskLsit.AddRange(sales);
                //获取YD销售数据
                sales = GetYDOrders(firstDate.ToDateTime().Date, localSKUList, shopList);
                saleskLsit.AddRange(sales);




                List<OL_EcommerceOrder> sourceData = new List<OL_EcommerceOrder>();
                sourceData = saleskLsit;



                //获取目标数据
                Filters.Clear();
                Filters.Add(
                //13:>,14>=15:<,16<=
                new OL_FilterDTO() { ControlId = "68ef049b3c333678d6a3cfd6", DataType = 15, SpliceType = 1, FilterType = 14, Value = firstDate }//FDATE字段过滤日开
            );
                List<OL_EcommerceOrder> targetData = await QueryAsync<OL_EcommerceOrder>(queryOption, tableField, SqlDb);

                //获取维护好的平台代码
                ConString = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
                SqlDb = (SqlServerHelper)DbHelperFactory.GetDbHelper(EFCore.Sharding.DatabaseType.SqlServer, ConString);
                var platforms = this.SqlDb.GetListBySql<Base_ConfigParameter>(@$"SELECT * FROM  Base_ConfigParameter(NOLOCK) WHERE Code='NotUpdateLogisticsSellerID'").First().Value.Split(",");

                targetData.ForEach(x =>
                {
                    //平台
                    List<AssTable> table = x.Platform.ToObject<List<AssTable>>();
                    if (!table.IsNullOrEmpty() && table.Count > 0) x.Platform = table.First().sid;
                    else x.Platform = "";
                    //店铺
                    table = x.Seller.ToObject<List<AssTable>>();
                    if (!table.IsNullOrEmpty() && table.Count > 0) x.Seller = table.First().sid;
                    else x.Seller = "";
                    //SKU
                    table = x.SKU.ToObject<List<AssTable>>();
                    if (!table.IsNullOrEmpty() && table.Count > 0) x.SKU = table.First().sid;
                    else x.SKU = "";
                    //MSKU
                    table = x.MSKU.ToObject<List<AssTable>>();
                    if (!table.IsNullOrEmpty() && table.Count > 0) x.MSKU = table.First().sid;
                    else x.MSKU = "";
                    //将不需要更新物流信息的店铺按照万联的数据去赋值
                    if (platforms.Contains(x.SellerId))
                    {
                        var o = sourceData.Where(y => y.ID == x.ID);
                        if (!o.IsNullOrEmpty() && o.Count() > 0)
                        {
                            var first = o.First();
                            first.CountryCode =x.CountryCode;
                            first.Province = x.Province;
                            first.City = x.City;
                            first.Address1 = x.Address1;
                            first.Address2 = x.Address2;
                            first.Address3 = x.Address3;
                            first.Zipcode = x.Zipcode;
                            first.Doorplate = x.Doorplate;
                            first.Company = x.Company;
                            first.Recipient = x.Recipient;
                            first.Phone1 = x.Phone1;
                            first.Phone2 = x.Phone2;
                            first.Email = x.Email;
                            first.TrackingCode = x.TrackingCode;
                        }

                    }

                });


                var ww = targetData.GroupBy(x => x).Where(x => x.Count() > 1);
                if (this.State > 0 && sourceData.Count > 0)
                {
                    //更新
                    #region
                    List<OL_EcommerceOrder> updataItem = sourceData.Intersect(targetData, new ComparerFromKeys<OL_EcommerceOrder>(Keys, "RowId")).ToList();//获取交集(更新项)
                    List<OL_RowDTO> updataData = ConvertOL_Row(updataItem, tableField);//需要更新的数据集合
                    ExecuteNoQuery<OL_RowDTO>(updataData, upDateOption, SqlDb);//执行更新
                    #endregion

                    //新增
                    #region
                    List<OL_EcommerceOrder> insertItem = sourceData.Except(targetData, new ComparerFromKey<OL_EcommerceOrder>(indexFields.First(), "RowId")).ToList();//获取源数据对目标数据的差集(新增项)
                    List<OL_RowDTO> insertData = ConvertOL_Row(insertItem, tableField);//需要新增的数据集合
                    ExecuteNoQuery<OL_RowDTO>(insertData, insertOption, SqlDb);//执行插入行
                    #endregion

                    //删除
                    #region
                    List<OL_EcommerceOrder> deleteItem = targetData.Except(sourceData, new ComparerFromKey<OL_EcommerceOrder>(indexFields.First(), "RowId")).ToList();//获取目标数对据源数据的差集(删除项)
                    List<OL_EcommerceOrder> repeatItem = targetData.GroupBy(x => x.GetPropertyValue(indexFields.First())).Where(x => x.Count() > 1).Select(x => x.FirstOrDefault()).ToList();
                    //将重复的项也一起加入删除的列表
                    deleteItem.AddRange(repeatItem);
                    //筛选出删除列表中重复的项
                    var temp = deleteItem.GroupBy(x => x.GetPropertyValue(indexFields.First())).Where(x => x.Count() > 1).Select(x => x.FirstOrDefault()).ToList();
                    deleteItem.AddRange(temp);
                    List<OL_RowDTO> deleteData = ConvertOL_Row(deleteItem, tableField);//需要删除的数据集合
                    ExecuteNoQuery<OL_RowDTO>(deleteData, deleteOption, SqlDb);//执行删除行
                    #endregion

                    //同步数据库
                    SqlDBInterfaceBusiness sqlDBInterface = new SqlDBInterfaceBusiness(Keys);
                    sqlDBInterface.ExecuteInterface<OL_EcommerceOrder>(sourceData, "SD_OL_EcommerceOrder", $"WHERE CONVERT(date,OrderDate) >= '{firstDate}'");
                }
            }


            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }



        public List<OL_EcommerceOrder> GetOZOrders(DateTime firstDate, List<LocalSKU> localSKUList, List<OL_Shop> shopList)
        {
            List<OL_EcommerceOrder> dataList = new List<OL_EcommerceOrder>();
            this.SqlDb._conStrings[0] = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
            //订单数据
            List<ReportPostingsCreate> orderList = this.SqlDb.GetListBySql<ReportPostingsCreate>(@$"SELECT * FROM SD_OZ_ReportPostingsCreate WHERE CONVERT(datetime,AcceptedForProcessing) >= '{firstDate}'");
            //产品编码
            List<RE_Product> prdList = this.SqlDb.GetListBySql<RE_Product>(@$"SELECT * FROM SD_RE_Product");

            //类型转换
            foreach (var item1 in orderList)
            {
                OL_EcommerceOrder row = new OL_EcommerceOrder();

                row.Order = item1.OrderNumber;
                if (item1.Status == "Delivered") row.State = "已交付";
                else if (item1.Status == "In transit" || item1.Status == "Доставляется") row.State = "运输中";
                else if (item1.Status == "Awaiting packaging") row.State = "待包装";
                else if (item1.Status == "Canceled") row.State = "已取消";
                else if (item1.Status == "Awaiting shipment") row.State = "待发货";
                else if (item1.Status == "Waiting at the pick-up point") row.State = "待取货";
                else if (item1.Status == "Courier is on the way") row.State = "送货中";
                else if (item1.Status == "Handing over to the courier") row.State = "送货中";
                else row.State = item1.Status;
                row.OriginallyState = item1.Status;
                row.Shipment = item1.ShipmentNumber;
                row.ShipmentType = item1.LogType;
                row.OrderDate = item1.AcceptedForProcessing;
                row.ShipmentDate = item1.ActualDateOfHandingOverToDelivery;
                //店铺平台
                var s = shopList.Where(x => x.ID == item1.SellerId);
                if (!s.IsNullOrEmpty())
                {
                    row.Seller = s.First().RowId;
                    row.Platform = s.First().Platform_;
                }
                row.ProductNumber = item1.ArticleCode;
                //仓库产品代码
                var p = prdList.Where(x => x.reference_no == item1.ArticleCode);
                if (!p.IsNullOrEmpty())
                {
                    row.StockNumber = p.First().product_sku;
                }
                row.SKU = "";
                row.Qty = item1.Quantity.ToInt();
                row.ProductName = item1.ProductName;
                //平台品类
                var t1 = GetEURPrdTypeAndBrand(item1.ArticleCode);
                row.ProductType = t1.Item1;
                row.ProductBrand = t1.Item2;

                row.PaymentType = "";
                row.Price = (decimal)item1.ShipmentAmount.ToDouble();
                row.Currency = item1.ShipmentCurrencyCode;
                row.Discount = item1.DiscountRUB.IsNullOrEmpty() ? 0 : (decimal)item1.DiscountRUB.ToDouble();
                row.PriceBeforeDiscount = item1.ProductPriceBeforeDiscounts.IsNullOrEmpty() ? 0 : (decimal)item1.ProductPriceBeforeDiscounts.ToDouble();
                row.SellerId = item1.SellerId;
                row.DataSource = "OZON";
                row.ID = item1.id;
                dataList.Add(row);
            }
            return dataList;
        }

        public List<OL_EcommerceOrder> GetWBOrders(DateTime firstDate, List<LocalSKU> localSKUList, List<OL_Shop> shopList)
        {
            List<OL_EcommerceOrder> dataList = new List<OL_EcommerceOrder>();
            this.SqlDb._conStrings[0] = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");

            //发货报告明细
            List<WB_OrdersDTO.Orders> orderList = this.SqlDb.GetListBySql<WB_OrdersDTO.Orders>(@$"SELECT * FROM SD_WB_Orders WHERE CONVERT(datetime,[createdAt]) >= '{firstDate}'");
            //产品编码
            List<RE_Product> prdList = this.SqlDb.GetListBySql<RE_Product>(@$"SELECT * FROM SD_RE_Product");
            //类型转换
            foreach (var item1 in orderList)
            {
                OL_EcommerceOrder row = new OL_EcommerceOrder();

                row.Order = item1.rid;
                row.State = item1.status_S;
                row.OriginallyState = item1.status_S;
                row.Shipment = item1.id;
                row.ShipmentType = item1.deliveryType.ToUpper();
                row.OrderDate = item1.createdAt;
                row.ShipmentDate = item1.shipmentDate;
                //店铺平台
                var s = shopList.Where(x => x.ID == "Wildberries");
                if (!s.IsNullOrEmpty())
                {
                    row.Seller = s.First().RowId;
                    row.Platform = s.First().Platform_;
                }
                row.ProductNumber = item1.article;

                //仓库产品代码
                var p = prdList.Where(x => x.reference_no == item1.article);
                if (!p.IsNullOrEmpty())
                {
                    row.StockNumber = p.First().product_sku;
                }
                row.SKU = "";
                row.Qty = 1;
                row.ProductName = ""; ;
                //平台品类
                var t1 = GetEURPrdTypeAndBrand(item1.article);
                row.ProductType = t1.Item1;
                row.ProductBrand = t1.Item2;

                row.PaymentType = "";
                row.Price = (decimal)item1.convertedPrice.ToDouble();
                row.Currency = "RUB";
                row.Discount = 0;
                row.PriceBeforeDiscount = 0;
                row.SellerId = "Wildberries";
                row.DataSource = "Wildberries";
                row.ID = item1.id;
                dataList.Add(row);

            }
            return dataList;
        }


        public List<OL_EcommerceOrder> GetYDOrders(DateTime firstDate, List<LocalSKU> localSKUList, List<OL_Shop> shopList)
        {
            List<OL_EcommerceOrder> dataList = new List<OL_EcommerceOrder>();
            this.SqlDb._conStrings[0] = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
            //订单明细
            List<YDOrdersDTO.Orders> orderList = this.SqlDb.GetListBySql<YDOrdersDTO.Orders>(@$"SELECT * FROM SD_YD_Orders WHERE CONVERT(datetime,[creationDate]) >='{firstDate}'");
            //产品编码
            List<RE_Product> prdList = this.SqlDb.GetListBySql<RE_Product>(@$"SELECT * FROM SD_RE_Product");
            //类型转换
            foreach (var item1 in orderList)
            {
                OL_EcommerceOrder row = new OL_EcommerceOrder();

                row.Order = item1.id;
                row.State = item1.status;
                row.OriginallyState = item1.status;
                row.Shipment = item1.id;
                row.ShipmentType = item1.ShipmentType;
                row.OrderDate = item1.creationDate;
                row.ShipmentDate = item1.shipments_shipmentDate;
                //店铺平台
                var s = shopList.Where(x => x.ID == item1.SellerId);
                if (!s.IsNullOrEmpty())
                {
                    row.Seller = s.First().RowId;
                    row.Platform = s.First().Platform_;
                }
                row.ProductNumber = item1.offerId;
                //仓库产品代码
                var p = prdList.Where(x => x.reference_no == item1.offerId);
                if (!p.IsNullOrEmpty())
                {
                    row.StockNumber = p.First().product_sku;
                }
                row.SKU = "";
                row.Qty = item1.count.ToInt();
                row.ProductName = item1.offerName;
                //平台品类
                var t1 = GetEURPrdTypeAndBrand(item1.offerId);
                row.ProductType = t1.Item1;
                row.ProductBrand = t1.Item2;

                row.PaymentType = item1.paymentType;
                row.Price = (decimal)item1.buyerPrice.ToDouble() + (decimal)item1.promosSubsidy.ToDouble();
                row.Currency = item1.currency;
                row.Discount = item1.buyerPriceBeforeDiscount.ToDouble().IsNullOrEmpty() || item1.buyerPriceBeforeDiscount.ToDouble() == 0 ? 0 : (decimal)item1.buyerPriceBeforeDiscount.ToDouble() - (decimal)item1.buyerPrice.ToDouble();
                row.PriceBeforeDiscount = item1.buyerPriceBeforeDiscount.ToDouble().IsNullOrEmpty() || item1.buyerPriceBeforeDiscount.ToDouble() == 0 ? 0 : (decimal)item1.buyerPriceBeforeDiscount.ToDouble();
                row.SellerId = item1.SellerId;
                row.DataSource = "Yandex";
                row.ID = item1.ID_;
                dataList.Add(row);

            }
            return dataList;
        }


        private (string, string) GetEURPrdTypeAndBrand(string code)
        {
            string type = "";
            string brand = "";
            if (code.Contains("TIH"))
            {  //品类
                type = "电磁炉";

                //品牌
                brand = "Tecasa";
            }
            else if (code.Contains("TCH"))
            {
                //品类
                type = "电陶炉";

                //品牌
                brand = "Tecasa";
            }
            else if (code.Contains("SPF01"))
            {
                //品类
                type = "热水器";

                //品牌
                brand = "Superflame";
            }
            else if (code.Contains("SPF02"))
            {
                //品类
                type = "热水器";

                //品牌
                brand = "Mizudo";
            }
            else if (code.Contains("CB."))
            {
                //品类
                type = "壁挂炉";

                //品牌
                brand = "Mizudo";
            }
            else
            {
                //品类
                type = "";
                //品牌
                brand = "";
            }
            return (type, brand);

        }

        public List<OL_EcommerceOrder> GetAMZOrders(DateTime firstDate, List<LocalSKU> localSKUList, List<OL_Shop> shopList)
        {
            List<OL_EcommerceOrder> dataList = new List<OL_EcommerceOrder>();
            this.SqlDb._conStrings[0] = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
            //订单明细
            List<AMZOrderDetail> orderList = this.SqlDb.GetListBySql<AMZOrderDetail>(@$"SELECT * FROM V_LX_WW_AMZOrderDetail WHERE CONVERT(date,[purchase_date_local]) >='{firstDate}'");
            try
            {
                //类型转换
                foreach (var item1 in orderList)
                {
                    OL_EcommerceOrder row = new OL_EcommerceOrder();

                    row.Order = item1.amazon_order_id;
                    row.State = item1.order_status;
                    row.OriginallyState = item1.order_status;
                    row.Shipment = "";
                    row.ShipmentType = "";
                    row.OrderDate = item1.purchase_date_local;
                    row.ShipmentDate = "";
                    //店铺平台
                    var s = shopList.Where(x => x.Name == item1.seller_name);
                    if (!s.IsNullOrEmpty())
                    {
                        row.Seller = s.First().RowId;
                        row.Platform = s.First().Platform_;
                        row.SellerId = s.First().ID;
                    }
                    row.ProductNumber = item1.seller_sku;
                    //仓库产品代码
                    row.StockNumber = "";
                    row.SKU = "";
                    row.Qty = item1.quantity_ordered.ToInt();
                    row.ProductName = item1.product_name;
                    //平台品类
                    //var t1 = GetEURPrdTypeAndBrand(item1.offerId);
                    //row.ProductType = t1.Item1;
                    //row.ProductBrand = t1.Item2;

                    row.PaymentType = "";
                    row.Price = (decimal)item1.unit_price_amount.ToDouble() - (decimal)item1.item_discount.ToDouble() - (decimal)item1.shipping_discount_amount.ToDouble();
                    row.Currency = item1.currency;
                    row.PriceBeforeDiscount = item1.unit_price_amount.ToDouble().IsNullOrEmpty() || item1.unit_price_amount.ToDouble() == 0 ? 0 : (decimal)item1.unit_price_amount.ToDouble();
                    row.Discount = !row.PriceBeforeDiscount.IsNullOrEmpty() && row.PriceBeforeDiscount != 0 ? 1 - row.Price / row.PriceBeforeDiscount : 0;
                    row.ID = item1.amazon_order_id + item1.seller_name + item1.seller_sku;
                    row.DataSource = "领星";

                    row.CountryCode = item1.country;
                    row.Province = item1.state_or_region;
                    row.City = item1.city;
                    row.Address1 = item1.address_line1;
                    row.Address2 = item1.address_line2;
                    row.Address3 = item1.address_line3;
                    row.Zipcode = item1.postal_code;
                    row.Doorplate = "";
                    row.Company = "";
                    row.Recipient = item1.buyer_name;
                    row.Phone1 = item1.phone;
                    row.Phone2 = "";
                    row.Email = "";
                    row.TrackingCode = item1.tracking_number;

                    dataList.Add(row);

                }
            }
            catch (Exception e)
            {

            }
            return dataList;
        }

        public List<OL_EcommerceOrder> GetECOrders(DateTime firstDate, List<LocalSKU> localSKUList, List<OL_Shop> shopList)
        {
            List<OL_EcommerceOrder> dataList = new List<OL_EcommerceOrder>();
            this.SqlDb._conStrings[0] = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
            //原平台的订单明细
            List<order_details> orderList = this.SqlDb.GetListBySql<order_details>(@$"SELECT * FROM [V_EC_WW_OrderDetails] WHERE CONVERT(date,[date_create_platform]) >='{firstDate}' AND is_merge  !='拆分的订单' AND is_merge !='合并订单' AND [platform]!='amazon'  AND platform_user_name not like  '%亚马逊%'");
            //易仓同步的订单
            //List<order_details> orderList = this.SqlDb.GetListBySql<order_details>(@$"SELECT * FROM [V_EC_WW_OrderDetails] WHERE CONVERT(date,[date_create_platform]) >='{firstDate}'");
            try
            {
                //类型转换
                foreach (var item1 in orderList)
                {
                    OL_EcommerceOrder row = new OL_EcommerceOrder();

                    row.Order = item1.refrence_no;
                    if (!item1.WMSOorder.IsNullOrEmpty() && item1.status == "待发货")
                    {
                        row.State = "已发货";
                    }
                    else
                    {
                        row.State = item1.status;
                    }
                    row.OriginallyState = item1.status;
                    row.Shipment = "";
                    row.ShipmentType = "";
                    row.OrderDate = item1.date_create_platform;
                    row.ShipmentDate = "";
                    //店铺平台
                    var s = shopList.Where(x => x.RowId == item1.OLSeller);
                    if (!s.IsNullOrEmpty())
                    {
                        row.Seller = s.First().RowId;
                        row.Platform = s.First().Platform_;
                        row.SellerId = s.First().ID;
                    }
                    else
                    {

                        row.SellerId = item1.platform_user_name;

                    }
                    row.ProductNumber = item1.product_sku_org.IsNullOrEmpty() ? item1.product_sku_list : item1.product_sku_org;
                    //仓库产品代码
                    row.StockNumber = item1.product_sku_list;
                    row.SKU = "";
                    row.Qty = item1.qty.ToInt();
                    row.ProductName = item1.product_title;
                    //平台品类
                    //var t1 = GetEURPrdTypeAndBrand(item1.offerId);
                    //row.ProductType = t1.Item1;
                    //row.ProductBrand = t1.Item2;

                    //订单总金额(含税不含折扣)
                    var amountpaid = item1.amountpaid.IsNullOrEmpty() ? 0 : (decimal)item1.amountpaid.ToDouble();
                    //单价(含税含折扣)
                    var unit_price = item1.unit_price.IsNullOrEmpty() ? 0 : (decimal)item1.unit_price.ToDouble();
                    var discount_val = item1.discount_val.IsNullOrEmpty() ? 0 : (decimal)item1.discount_val.ToDouble();
                    var tax = item1.tax.IsNullOrEmpty() ? 0 : (decimal)item1.tax.ToDouble();

                    row.PaymentType = "";
                    //折前价为不含税价需要减去税率，如果是多个产品的情况下，需要算出本产品的价格占比 乘 订单的总税费得出该产品的税费再减去，得出不含税价格
                    row.PriceBeforeDiscount = unit_price > 0 && amountpaid > 0 ? unit_price - unit_price / amountpaid * tax : 0;
                    //先算出订单折扣占比，然后用不含税价格减去折扣得出最终售价
                    row.Price = row.PriceBeforeDiscount > 0 && amountpaid > 0 ? row.PriceBeforeDiscount - unit_price / amountpaid * discount_val : 0;
                    row.Currency = item1.currency;
                    row.Discount = unit_price > 0 && amountpaid > 0 ? unit_price / amountpaid * discount_val : 0;
                    row.ID = item1.op_id;

                    row.CountryCode = item1.order_address_country_code;
                    row.Province = item1.order_address_state;
                    row.City = item1.order_address_city_name;
                    row.Address1 = item1.order_address_line1;
                    row.Address2 = item1.order_address_line2;
                    row.Address3 = item1.order_address_line3;
                    row.Zipcode = item1.order_address_postal_code;
                    row.Doorplate = item1.order_address_doorplate;
                    row.Company ="";
                    row.Recipient = item1.buyer_name;
                    row.Phone1 = item1.order_address_phone;
                    row.Phone2 = "";
                    row.Email = item1.buyer_mail;
                    row.TrackingCode = item1.shipping_method_no;

                    row.EC_creater_user_name = item1.creater_user_name;
                    row.EC_platform = item1.platform;
                    row.EC_is_merge = item1.is_merge;
                    row.EC_platform_user_name = item1.platform_user_name;
                    row.DataSource = "易仓";
                    dataList.Add(row);

                }
            }
            catch (Exception e)
            {

            }
            return dataList;
        }
        public List<OL_EcommerceOrder> GetXMOrders(DateTime firstDate, List<LocalSKU> localSKUList, List<OL_Shop> shopList)
        {
            List<OL_EcommerceOrder> dataList = new List<OL_EcommerceOrder>();
            this.SqlDb._conStrings[0] = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
            //订单明细
            List<XM_OrderLIst.OrderList> orderList = this.SqlDb.GetListBySql<XM_OrderLIst.OrderList>(@$"SELECT * FROM SD_XM_OrderList WHERE ctime >='{firstDate}'");
            try
            {
                //类型转换
                foreach (var item1 in orderList)
                {
                    OL_EcommerceOrder row = new OL_EcommerceOrder();

                    row.Order = item1.orderId;
                    row.State = item1.productList_status;
                    row.OrderDate = item1.productList_status;
                    row.Shipment = "";
                    row.ShipmentType = "";
                    row.OrderDate = item1.ctime;
                    row.ShipmentDate = "";
                    //店铺平台
                    var s = shopList.Where(x => x.ID == item1.partnerId);
                    if (!s.IsNullOrEmpty())
                    {
                        row.Seller = s.First().RowId;
                        row.Platform = s.First().Platform_;
                        row.SellerId = s.First().ID;
                    }
                    row.ProductNumber = item1.productList_pid;
                    //仓库产品代码
                    row.StockNumber = "";
                    row.SKU = "";
                    row.Qty = (decimal)item1.productList_count.ToDouble();
                    row.ProductName = item1.productList_name;
                    //平台品类
                    //var t1 = GetEURPrdTypeAndBrand(item1.offerId);
                    //row.ProductType = t1.Item1;
                    //row.ProductBrand = t1.Item2;


                    row.PaymentType = "";
                    row.PriceBeforeDiscount = item1.productList_productPrice;
                    row.Price = item1.productList_price;
                    row.Currency = item1.productList_name;
                    row.Discount = item1.couponReduce + item1.activityReduce + item1.redpacketReduce;
                    row.DataSource = "小米有品";

                    row.CountryCode = item1.address_country;
                    row.Province = item1.address_province;
                    row.City = item1.address_city+ item1.address_district;
                    row.Address1 = item1.address_area;
                    row.Address2 = item1.address_address;
                    row.Address3 = item1.address_addressName;
                    row.Zipcode = item1.address_zipcode;
                    row.Doorplate = "";
                    row.Company = "";
                    row.Recipient = item1.address_consignee;
                    row.Phone1 = item1.address_tel;
                    row.Phone2 = "";
                    row.Email = "";
                    row.TrackingCode = item1.LogisticsList_expressSn;


                    row.ID = row.Order + row.SellerId + row.ProductNumber;
                    dataList.Add(row);

                }
            }
            catch (Exception e)
            {

            }
            return dataList;
        }

        /// <summary>
        /// 将源数据根据字典映射关系转换成OL_RowDTO
        /// </summary>
        /// <typeparam name="T">源数据</typeparam>
        /// <param name="sourceData">源数据</param>
        /// <param name="map">Key为目标字段名称，Value为源字段名称</param>
        /// <returns></returns>
        public List<OL_RowDTO> ConvertOL_Row<T>(List<T> sourceData, Dictionary<string, string> map)
        {
            List<OL_RowDTO> list = new List<OL_RowDTO>();
            object rowId;
            foreach (var item in sourceData)
            {
                rowId = item.GetPropertyValue("RowId");
                //需要新增的数据
                OL_RowDTO row = new OL_RowDTO() { RowId = rowId.IsNullOrEmpty() ? null : rowId.ToString(), Controls = new List<Control>() };
                foreach (var c in map)
                {
                    //获取字段的键值做判断
                    var field = Keys.Where(x => x.TField == c.Key).ToList();
                    string isKey = "";
                    if (field.Count > 0) isKey = field.First().Type;
                    //判断对象的字段是否存在
                    if (item.ContainsProperty(c.Value) && isKey != "N")
                    {
                        //存在则添加数据
                        row.Controls.Add(new Control() { ControlId = c.Key, Value = item.GetPropertyValue(c.Value) });
                    }
                }
                list.Add(row);
            }
            return list;
        }
        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }

}
